package ee.rumba.iPhoneShop.dictionary;

import ee.rumba.iPhoneShop.artwork.Artwork;

import java.io.IOException;
import java.io.File;
import java.io.BufferedReader;
import java.io.FileReader;

public class Main {
  public static void printUsage() {
    System.out.println("Usage: java -jar iPhoneShop.jar KDICT command");
    System.out.println("   dump /path/to/english-unigrams.dat");
    System.out.println(" create /path/to/textDBFile.txt    (must be UTF-8 and \\n terminated lines)");
    System.exit(1);
  }

  public static void main(String[] args) throws Exception {
    if (args.length < 2) {
      printUsage();
    }
    File file = new File(args[1]);
    String command = args[0].toUpperCase();

    if (!file.canRead()) {
      System.out.println("Unable to read file " + file.getAbsolutePath());
      printUsage();
    }

    if (command.trim().toUpperCase().equals("DUMP")) {
      iDictionary iDict = iDictionary.parseUnigramsDat(file);
      iDict.writeTextDump(new File(file.getName() + ".txt"));
    } else if (command.trim().toUpperCase().equals("CREATE")) {
      BufferedReader br = new BufferedReader(new FileReader(file));
      ee.rumba.iPhoneShop.dictionary.iDictionary idict = new iDictionary();
      String header = br.readLine();
      if (!header.equals("UTF8Word\tX-Boolean\tWeight")) throw new IllegalArgumentException("Source file is not valid\nit must have header and format\n\"UTF8Word\\tX-Boolean\\tWeight\\n\"");
      
      while (true) {
        String s = br.readLine();
        if (s == null) break;
        String[] parts = s.split("\t");
        if (parts.length != 3) System.out.println("debug: Unknown line: \"" + s + "\"");

        String utf8Word = new String(parts[0].getBytes(), "UTF-8");
        boolean xboolean = parts[1].equals("true");
        int weight = Integer.parseInt(parts[2]);
        idict.addiWord(new iWord(utf8Word, weight, xboolean));
      }
      idict.writeUnigramsDat(new File("en_GB-unigrams.dat"));
      idict.writeUnigramsIdx(new File("en_GB-unigrams.idx"));
      idict.writeStemsDat(new File("en_GB-stems.dat"));
      idict.writeTextDump(new File("english-unigrams.dat.debug.txt"));
      System.out.println("Created dictionary, please check english-unigrams.dat.debug.txt before copying binary files to iPhone");
    } else {
      printUsage();
    }
  }
}
